package com.zyh.exam.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.utils.DateUtils;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.question.domain.ExamQuestion;
import com.zyh.question.mapper.ExamQuestionMapper;
import com.zyh.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zyh.exam.mapper.ExamPaperMapper;
import com.zyh.exam.domain.ExamPaper;
import com.zyh.exam.service.IExamPaperService;

/**
 * 试卷管理Service业务层处理
 *
 * @author zyh
 * @date 2025-02-20
 */
@Service
public class ExamPaperServiceImpl extends ServiceImpl<ExamPaperMapper, ExamPaper> implements IExamPaperService {
    @Autowired
    private ExamPaperMapper examPaperMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    public final Logger logger = LoggerFactory.getLogger(ExamPaperServiceImpl.class);


    /**
     * 发布试卷
     *
     * @param updateExamPaper
     * @return
     */
    @Override
    public AjaxResult publishedPaper(ExamPaper updateExamPaper) {
        // 传来的状态值为1，代表要发布试卷
        if ("1".equals(updateExamPaper.getIsPublished())) {
            // 如果试卷有开始时间和结束时间
            if (updateExamPaper.getStartTime() != null && updateExamPaper.getEndTime() != null) {
                Date startTime = updateExamPaper.getStartTime();
                Date endTime = updateExamPaper.getEndTime();
                // 如果当前时间小于试卷开始时间
                if (DateUtils.getNowDate().after(startTime)) {
                    return AjaxResult.error("发布时间小于试卷开始时间，请检查或修改开始时间！");
                }
            }
            updateExamPaper.setIsPublished("1");
            updateExamPaper.setPublishedBy(SecurityUtils.getUsername());
            updateExamPaper.setPublishedTime(DateUtils.getNowDate());
            return examPaperMapper.updateExamPaper(updateExamPaper) > 0 ?
                    AjaxResult.success("发布成功！") : AjaxResult.error("发布失败！");
        } else {
            // 代表传入的状态是0，代表要取消发布
            updateExamPaper.setIsPublished("0");
            updateExamPaper.setPublishedBy(null);
            updateExamPaper.setPublishedTime(null);
            return examPaperMapper.updateExamPaper(updateExamPaper) > 0 ?
                    AjaxResult.success("取消发布成功！") : AjaxResult.error("取消发布失败！");
        }
    }

    /**
     * 查询试卷管理
     *
     * @param id 试卷管理主键
     * @return 试卷管理
     */
    @Override
    public ExamPaper selectExamPaperById(Long id) {
        return examPaperMapper.selectExamPaperById(id);
    }

    /**
     * 查询试卷管理列表
     *
     * @param examPaper 试卷管理
     * @return 试卷管理
     */
    @Override
    public List<ExamPaper> selectExamPaperList(ExamPaper examPaper) {
        return examPaperMapper.selectExamPaperList(examPaper);
    }

    /**
     * 新增试卷管理
     *
     * @param examPaper 试卷管理
     * @return 结果
     */
    @Override
    public int insertExamPaper(ExamPaper examPaper) {
        examPaper.setStatus("0");       // 默认未开始
        examPaper.setIsPublished("0");  // 默认不发布
        examPaper.setPublishedTime(null);
        examPaper.setPublishedBy(null);
        examPaper.setCreateTime(DateUtils.getNowDate());
        examPaper.setCreateBy(SecurityUtils.getUsername());
        examPaper.setDelFlag("0");
        return examPaperMapper.insertExamPaper(examPaper);
    }

    /**
     * 修改试卷管理
     *
     * @param examPaper 试卷管理
     * @return 结果
     */
    @Override
    public int updateExamPaper(ExamPaper examPaper) {
        Date startTime = examPaper.getStartTime();
        Date now = new Date();
        if ((Objects.nonNull(startTime) && startTime.after(now)) || Objects.isNull(startTime)) {
            // 如果开始时间大于当前时间，则修改状态为未开始
            examPaper.setStatus("0");
        }
        examPaper.setUpdateBy(SecurityUtils.getUsername());
        examPaper.setUpdateTime(DateUtils.getNowDate());
        return examPaperMapper.updateExamPaper(examPaper);
    }

    /**
     * 批量删除试卷管理
     *
     * @param ids 需要删除的试卷管理主键
     * @return 结果
     */
    @Override
    public int deleteExamPaperByIds(Long[] ids) {
        // 删除试卷的同时要将所有改试卷下的选项也逻辑删除
        List<Long> idList = new ArrayList<>();
        for (Long id : ids) {
            List<ExamQuestion> questionList = examQuestionMapper.selectExamQuestionByPaperId(id);
            if (questionList != null && !questionList.isEmpty()) {
                idList.addAll(questionList.stream().map(ExamQuestion::getId).collect(Collectors.toList()));
            }
        }
        logger.info("idList-->{}", idList);
        // 将集合转换为数组
        if (!idList.isEmpty()) {
            // 如果数组不为空
            examQuestionMapper.deleteExamQuestionByIds(idList.toArray(new Long[0]));
        }
        return examPaperMapper.deleteExamPaperByIds(ids);
    }

    /**
     * 删除试卷管理信息
     *
     * @param id 试卷管理主键
     * @return 结果
     */
    @Override
    public int deleteExamPaperById(Long id) {
        return examPaperMapper.deleteExamPaperById(id);
    }
}
